package com.core.transaction;

import java.io.Serializable;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;


@Transactional
@Interceptor
public class TransactionalInterceptor implements Serializable {


//	public static EntityManager getEntityManager() {
//		return com.transaction.EntityManagerClass.getEntityManager();
//	}


	private static final long serialVersionUID = 1889073600432817015L;
	protected final static EntityManagerFactory EMF;
	static {
		EMF = Persistence.createEntityManagerFactory("aqarat");
	}
	@AroundInvoke
	public Object manageTransaction(InvocationContext context) throws Throwable {
		Object result = null;
		EntityManager entityManager =EMF.createEntityManager();
		if (entityManager != null) {
			EntityTransaction transaction = null;
			boolean isTransactionActive = false;
			// for Transaction Propagation
			try {
//				transaction = EntityManagerClass.getEntityManager().getTransaction();
				transaction = entityManager.getTransaction();
				if (transaction == null || !transaction.isActive()) {
					transaction = entityManager.getTransaction();
					transaction.begin();
					isTransactionActive = true;
				}
				result = context.proceed();
				if (isTransactionActive) {
					transaction.commit();
					System.out.println("commited");
				}
			} catch (Throwable t) {
				if (isTransactionActive) {
					transaction.rollback();
				}
				throw t;
			}
		} else {
			result = context.proceed();
		}
		return result;
	}
}
